define([
    'ELEMENT',
    'ELEMENTICON',
    'ELEMENTCN',
    'layer',
    'jquery',
    'Promise',
    'MenuItem',
    "MuShowImg",
    "MuTreeInput",
    "MuFileUpload",
    "MuAvatarUpload",
    "MuCascader",
    "MuTreeSelect",
    "MuIcon",
    "MuForm",
    "echarts",
    "NumberRange",
    "KeyValue",
    "MuAvatarUploads",
    "mutable",
    "muform",
    "WangEditor"
], function (ELEMENT,
             ELEMENTICON,
             ELEMENTCN,
             layer,
             $,
             Promise,
             MenuItem,
             MuShowImg,
             MuTreeInput,
             MuFileUpload,
             MuAvatarUpload,
             MuCascader,
             MuTreeSelect,
             MuIcon,
             MuForm,
             echarts,
             NumberRange,
             KeyValue,
             MuAvatarUploads,
             mutable,
             muform,
             WangEditor
) {
    const {ElLoading,ElMessage,ElMessageBox } = ELEMENT;
    const common = {
        config:{
            color:{
            }
        },
        async load(app, component = []) {
            app.use(ELEMENT,{
                locale: ELEMENTCN
            });
            if(component.includes('all')){
                component = [
                    'icon',
                    'ELEMENT',
                    'ELEMENTICON',
                    'ELEMENTCN',
                    'layer',
                    'jquery',
                    'Promise',
                    'MenuItem',
                    "MuShowImg",
                    "MuTreeInput",
                    "MuFileUpload",
                    "MuAvatarUpload",
                    "MuCascader",
                    "MuTreeSelect",
                    "MuIcon",
                    "MuForm",
                    "echarts",
                    "NumberRange",
                    "KeyValue",
                    "MuAvatarUploads",
                    "mutable",
                    "muform",
                    "WangEditor"
                ];
            }
            if(component.length>0){
                //加载图标
                if(component.includes('icon')){
                    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
                        // console.log(key)
                        app.component(key, component)
                    }
                }
                // console.log(999)
                for(let i=0;i<component.length;i++){
                    if(component[i]!='icon'){
                        let temcomponent = require(component[i])
                        // console.log(temcomponent)
                        app.component(component[i], temcomponent)
                    }
                }
                // console.log(888)
            }
            common.changeTheme(this.config.color)
            let that = this;
            window.getThumb = function (){
                return that.config.color
            }
            window.addEventListener('message', function (event) {
                let data = event.data;
                if (data.action) {
                    switch (data.action) {
                        case 'changeTheme':
                            that.changeTheme(data.data)
                            break;
                    }
                }
            })
            if (parent?.window?.getThumb) {
                let themeObj = parent.window.getThumb()
                this.changeTheme(themeObj)
            }
        },
        changeTheme(obj) {
            // console.log(33333333333)
            if (!obj) {
                return
            }
            if (typeof obj === 'string') {
                // console.log(111111111)
                common.config.color['--el-color-primary'] = obj
                let rgb = common.hexToRgb(obj)
                let rgblight = common.rgbAdd(rgb,{r:57.3,g:29.1,b:0})
                let primary_light = common.rgbAdd(rgb,{r:-12.8,g:-31.6,b:-51})
                let primary_light5 = common.rgbAdd(rgb,{r:95,g:48,b:0})
                // console.log(rgb,'rrrrrrrrrrrrrrrrrrrrrrr')
                common.config.color['--el-color-primary-light-3'] = `rgb(${rgblight.r},${rgblight.g},${rgblight.b})`
                common.config.color['--el-color-primary-dark-2'] = `rgb(${primary_light.r},${primary_light.g},${primary_light.b})`
                common.config.color['--el-color-primary-light-5'] = `rgb(${primary_light5.r},${primary_light5.g},${primary_light5.b})`
                document.documentElement.style.setProperty('--el-color-primary', obj);
                document.documentElement.style.setProperty('--el-color-primary-light-3', `rgb(${rgblight.r},${rgblight.g},${rgblight.b})`);
                document.documentElement.style.setProperty('--el-color-primary-dark-2', `rgb(${primary_light.r},${primary_light.g},${primary_light.b})`);
                document.documentElement.style.setProperty('--el-color-primary-light-5', `rgb(${primary_light5.r},${primary_light5.g},${primary_light5.b})`);
            } else {
                // console.log(2222222)
                for (let key in obj) {
                    document.documentElement.style.setProperty(key, obj[key]);
                    common.config.color[key] = obj[key]
                }
            }
        },
        hexToRgb(hex){
            hex = hex.replace('#', '');

            // 将十六进制转换为十进制
            let r = parseInt(hex.substring(0, 2), 16);
            let g = parseInt(hex.substring(2, 4), 16);
            let b = parseInt(hex.substring(4, 6), 16);

            // 返回RGB字符串
            return {
                r: r,
                g: g,
                b: b
            };
        },
        rgbToHex(r, g, b){
            let hex = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
            return `#${hex}`;
        },
        rgbAdd(color1,color2){
            console.log(color1,'color1',color2,'color2')
            let r = Math.min(255, color1.r + color2.r);
            let g = Math.min(255, color1.g + color2.g);
            let b = Math.min(255, color1.b + color2.b);
            return { r, g, b };
        },
        /**
         * 弹窗
         * @param message
         * @param title
         * @param type
         * @param callback
         * @constructor
         */
        ElMessageBox(message,title='提示',type='warning',callback=null){
            if(typeof title === "function"){
                callback = title;
                title = '提示'
            }
            ElMessageBox({
                title: '提示',
                message: '确定要删除吗？',
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                showCancelButton:true,
                callback: (action) => {
                    if (action === 'confirm') {
                        if(callback){
                            callback(action)
                        }
                    }
                }
            })
        },
        /**
         * get请求
         * @param url
         * @param data
         * @returns {Promise}
         */
        get(url,data={},loading=false){
            if((typeof data)=='boolean'){
                loading = data;
                data = {}
            }
            if ((typeof url) !== "string") {
                data = url;
                url = Config.sub_url
            }
            if(!url){
                url = Config.sub_url
            }
            return common.request(url,"GET",data,loading)
        },
        /**
         * post请求
         * @param url
         * @param data
         * @returns {Promise}
         */
        post(url, data = {},loading=false) {
            if((typeof data)=='boolean'){
                loading = data;
                data = {}
            }
            if ((typeof url) !== "string") {
                data = url;
                url = Config.sub_url
            }
            if(!url){
                url = Config.sub_url
            }
            return common.request(url,"POST",data,loading)
        },
        getHandle(url, data = {},loading=false){
            if((typeof data)=='boolean'){
                loading = data;
                data = {}
            }
            if ((typeof url) !== "string") {
                data = url;
                url = Config.sub_url
            }
            if(!url){
                url = Config.sub_url
            }
            return common.requestHand(url,"GET",data,loading)
        },
        /**
         * 统一处理返回数据
         * @param url
         * @param data
         * @param loading
         * @param complete
         * @returns {Promise}
         */
        postHandle(url, data = {},loading=false,complete=null){
            if((typeof data)=='boolean'){
                loading = data;
                data = {}
            }
            if ((typeof url) !== "string") {
                data = url;
                url = Config.sub_url
            }
            if(!url){
                url = Config.sub_url
            }
            return common.requestHand(url,"POST",data,loading,complete)
        },
        /**
         * 处理返回数据
         * @param url
         * @param method
         * @param data
         * @param loading
         * @param complete
         * @returns {Promise}
         */
        requestHand(url, method = "GET", data = {},loading=false,complete=null){
            return new Promise(function (resolve, reject) {
                let options = {}
                let loadingInstance = null
                if(loading){
                    loadingInstance  = ElLoading.service(options)
                }
                // console.log(loading,'lllllllllllllllllllllllllll')
                $.ajax(url,{
                    method: method,
                    data: data,
                    success: function (res) {
                        if(res.code==1){
                            resolve(res.data)
                        }else{
                            common.error(res.msg)
                        }
                        // resolve(res)
                    },
                    error: function (res) {
                        reject(res)
                    },
                    complete: function (res) {
                        if(loading){
                            loadingInstance.close()
                        }
                        if(complete){
                            complete(res)
                        }
                    }
                })
            })
        },
        /**
         * 请求
         * @param url
         * @param method
         * @param data
         * @returns {Promise}
         */
        request(url, method = "GET", data = {},loading=false,complete=null) {
            return new Promise(function (resolve, reject) {
                let options = {}
                let loadingInstance = null
                if(loading){
                    loadingInstance  = ElLoading.service(options)
                }
                $.ajax(url,{
                    method: method,
                    data: data,
                    success: function (res) {
                        resolve(res)
                    },
                    error: function (res) {
                        reject(res)
                    },
                    complete: function (res) {
                        if(loading){
                            loadingInstance.close()
                        }
                        if(complete){
                            complete(res)
                        }
                    }
                })
            })
        },
        /**
         * 打开窗口
         * @param title
         * @param content
         * @param area
         * @param callback
         */
        open(title='', content='',area=['80%', '80%'], callback) {
            if((typeof area)=='function'){
                callback = area;
                area = ['80%', '80%'];
            }
            // if(callback!==undefined){
            //     window.callback = callback;
            // }
            // console.log(title,content,area,callback)
            console.log(area,'aaaaaaaaaaaaaaaaaaaaaaaaa')
            layer.open({
                type:2,
                title: title,
                content: content,
                area: area,
                callback:function (layero, index) {
                    console.log("callback")
                    if(callback){
                        callback(layero, index);
                    }
                },
                end:function (){
                    if(callback){
                        callback();
                    }
                },
                success:function (layero, index){
                    console.log('success')
                }

            })
        },
        close(){
            let index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },
        addObject(obj, newObj) {
            if(!obj){
                obj = {}
            }
            obj = common.copy( obj)
            for (let key in obj){
                if(key in newObj){
                    obj[key] = newObj[key]
                }
            }
            return obj
        },
        message(message,type='success',callback=null,duration=800){
            if((typeof callback)=='number'){
                duration = callback;
                callback = null;
            }
            ElMessage({
                message: message,
                type: type,
                duration:duration,
                onClose:callback,
            })
            // setTimeout(function () {
            //     if(callback){
            //         callback()
            //     }
            // },duration)
        },
        success(message,callback=null,duration=800){
            if(this.message){
                return this.message(message,'success',callback,duration)
            }
            return common.message(message,'success',callback,duration)
        },
        error(message,callback=null,duration=800){
            if(this.message){
                return this.message(message,'error',callback,duration)
            }
            return common.message(message,'error',callback,duration)
        },
        copy(data){
            if(typeof data=='object'){
                return JSON.parse(JSON.stringify(data))
            }
            if(typeof data=='string'){
                return data.slice();
            }
            return Number(data);

        },
        getHandleUrl(url){
            let newurl = `/app/${Config.plugin}/${Config.app}/${Config.controller}/${url}`
            let params = common.windowsGetParams()
            if(params){
                if(newurl.indexOf('?')==-1){
                    newurl += '?'+params
                }else{
                    newurl += '&'+params
                }
            }
            return newurl
        },
        windowsGetParams(getObj=false){
            let params = location.search;
            params = params.substr(1)
            let newParams = {}
            params.split('&').forEach(item=>{
                let itemArr = item.split('=')
                if(itemArr[0]!='ref'){
                    newParams[itemArr[0]] = itemArr[1]
                }
            })
            if(getObj){
                return newParams
            }
            let str = ''
            for(let key in newParams){
                str += key+'='+newParams[key]+'&'
            }
            str = str.slice(0,-1)
            return  str
        },
        //  公共方法不能使用common访问，只能使用this访问
        /**
         * 删除
         * @param row
         * @param pk
         */
        handleDelete(row,pk='id'){
            if(this.search?.form?.pk){
                pk = this.search.form.pk
            }
            let ids = ""
            if((typeof row)=='string'||(typeof row)=='number'){
                ids = row
            }
            if(Array.isArray(row)){
                ids = row.map(item=>item[pk]).join(',')
            }else if((typeof row)=='object'){
                ids = row[pk]
            }
            if(!ids){
                common.message('请选择要删除的项')
                return
            }
            let that = this;
            ElMessageBox({
                title: '提示',
                message: '确定要删除吗？',
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                showCancelButton:true,
                callback: (action) => {
                    console.log(action)
                    if (action === 'confirm') {
                        let url = common.getHandleUrl('del')
                        common.postHandle(url,{ids:ids}).then(res=>{
                            common.message('删除成功')
                            // console.log("删除成功------------")
                            that.getList();
                            // console.log(999999)
                        })
                    }
                }
            })
        },
        /**
         * 添加
         * @param area
         */
        handleAdd(area=['600px', '95%']){
            let params =common.windowsGetParams()
            let url = common.getHandleUrl('add')
            if(params){
                if(url.indexOf('?')==-1){
                    url += '?'+params
                }else{
                    url += '&'+params
                }
            }
            // console.log(url)
            let that = this
            common.open('添加',url,area,function (layero, index){
                that.getList()
            })
        },
        /**
         * 修改
         * @param row
         * @param area
         * @param pk
         */
        handleEdit(row,area=['600px', '95%'],pk='id'){
            pk = this.handleGetPk(pk)
            let url = common.getHandleUrl(`edit?ids=${row[pk]}`)
            let params =common.windowsGetParams()
            if(params){
                if(url.indexOf('?')==-1){
                    url += '?'+params
                }else{
                    url += '&'+params
                }
            }
            let that = this
            common.open('修改',url,area,function (layero, index){
                that.getList()
            })
        },
        /**
         * 获取列表
         */
        getList(loading=false){
            let data = {
                page:this.listObj.page,
                limit:this.listObj.limit,
                ...this.search.form
            }
            // console.log(data,'dddddddddddddddddd')
            common.postHandle(data,loading).then(res=>{
                if(res){
                    this.listObj.total = res.total
                    this.listObj.list = res.rows
                }else{
                    this.listObj.total = 0
                    this.listObj.list = []
                }
            })
        },
        refresh(){
            this.getList(true)
        },
        /**
         * 改变分页条数
         * @param e
         */
        handleSizeChange(e){
            this.listObj.limit = e
            this.getList()
        },
        /**
         * 改变页码
         * @param e
         */
        handleCurrentChange(e){
            this.listObj.page = e
            this.getList()
        },
        /**
         * 多选
         * @param e
         * @param pk
         */
        handleSelectionChange(e,pk='id'){
            if(this.search?.form?.pk){
                pk = this.search.form.pk
            }
            this.selectables = e.map(item=>item[pk])
        },
        /**
         * 获取pk
         * @param defaultPk
         * @returns {string}
         */
        handleGetPk(defaultPk = 'id'){
            if(this.search?.form?.pk){
                defaultPk = this.search.form.pk
            }
            return defaultPk
        },
        /**
         * 批量删除
         * @param pk
         */
        handleDels(pk='id'){
            if(this.search?.form?.pk){
                pk = this.search.form.pk
            }
            // console.log(this.selectables)
            if(this.selectables.length==0){
                common.message('请选择要删除的项')
                return
            }
            let ids = common.copy(this.selectables).join(',')
            // console.log(pk,ids)
            this.handleDelete(ids,pk)
            // this.handleDelete(ids,pk)
        },
        /**
         * 切换开关
         * @param row
         * @param field
         * @param pk
         */
        handleSwitchChange(row,field,pk='id'){
            if(this.search?.form?.pk){
                pk = this.search.form.pk
            }
            let newurl = common.getHandleUrl('multi')
            let that  = this
            common.post(newurl,{ids:row[pk],field:field}).then(res=>{
                if(res.code==1){
                    common.success(res.msg,()=>{
                        that.getList()
                    })
                }else{
                    common.error(res.msg,function (){
                        that.getList()
                    })
                }
            })
        },
        // 关闭窗口
        onCancel(){
            common.close()
        },
        onSubmitAdd(){
            let that  = this
            this.$refs.form.validate(valid=>{
                if( valid){
                    let url = Config.sub_url
                    console.log({row:common.copy(this.form)})
                    common.postHandle(url,{row:common.copy(this.form)},true).then(res=>{
                        that.success("添加成功",()=>{
                            common.close()
                        })
                    })
                }
            })
        },
        onSubmitEdit(){
            let that  = this
            this.$refs.form.validate(valid=>{
                if( valid){
                    let url = Config.sub_url
                    console.log({row:common.copy(this.form)})
                    common.postHandle(url,{row:common.copy(this.form)},true).then(res=>{
                        that.success("添加成功",()=>{
                            common.close()
                        })
                    })
                }
            })
        },
        resetSearch(){
            let search = this.search.list.map(item=>{
                item.value = ''
                return item
            })
            // console.log(search)
            this.search.list = search
            this.onSearch()
        },
        onSearch(){
            let filter = {}
            let op = {}
            this.search.list.forEach(item=>{
                if(item.value){
                    filter[item.name] = item.value
                    if(item.operate){
                        op[item.name] = item.operate
                    }else{
                        op[item.name] = '='
                    }
                }
            })
            this.search.form.filter  = filter
            this.search.form.op  = op
            this.listObj.page = 1
            this.getList(true);
        }
    }
    return common;
})